package com.eipc;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.AlertDialog.Builder;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckedTextView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Spinner;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.TabHost.TabContentFactory;

import com.eipc.info.R;
import com.eipc.model.Response;
import com.eipc.util.DBHelper;
import com.eipc.util.HttpManager;
import com.eipc.util.JsonParse;
import com.eipc.util.Tools;

/**
 * 
 * @author x_liaolijun
 *
 * 2010-9-4 上午11:41:23
 *  
 * SendActivity
 *
 */
public class SendActivity extends Activity implements OnClickListener,TabContentFactory{
	private final static int REUQEST_CODE_TAKE_PICTURE = 2;
	private int type;   //类型(由于重要通告和短信和我要报告一样的)
	private EditText mPerson;
	private EditText mContent;
	private Spinner mSendType;
	private Button mAdd;
	private Button mCamera;
	private Button mSend;
	private LayoutInflater mInflater;
	private Cursor mCursor;
	private InputStream mPictrueStream; //图片流
	private String mPersons = "";
	private DBHelper mDB;
	private Dialog mDialog;
	private AlertDialog.Builder mBuilder;
	private SimpleCursorAdapter mAdapter;
	private String mLeader;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		CommonActivity.isSend = true;
		setContentView(R.layout.import_notice_send);
		mBuilder = new Builder(this).setTitle(R.string.tip);
		Intent i = getIntent();
		if(i==null){
			type = ImportNoticeActivity.TYPE;
			mLeader = DBHelper.STATUS.LEADER_SMALL;
		}
		else{
			type = i.getIntExtra("type",ImportNoticeActivity.TYPE);
			mLeader = i.getStringExtra("leader");
		}
		initView();
	}
	
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		//接受照相的数据
		if(resultCode == RESULT_OK){
			if(requestCode == REUQEST_CODE_TAKE_PICTURE){
				ContentResolver resolver = getContentResolver();
				try {
					mPictrueStream = resolver.openInputStream(data.getData());
				}catch (FileNotFoundException e){
					e.printStackTrace();
				}
			}
		}
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		if(mCursor!=null) mCursor.close();
		if(mPictrueStream!=null)
			try {
				mPictrueStream.close();
			} catch (IOException e) {
			}
	}
	
	private void initView(){
		mPerson = (EditText)findViewById(R.id.et_person);
		mContent = (EditText)findViewById(R.id.et_content);
		mAdd = (Button)findViewById(R.id.btn_add);
		mCamera = (Button)findViewById(R.id.btn_camera);
		mSendType = (Spinner)findViewById(R.id.sp_send_type);
		mInflater = getLayoutInflater();
//		mDB = new DBHelper(this);
		mDB = DBHelper.getInstance(this);
		mSend = (Button)findViewById(R.id.btn_send);
		mAdd.setOnClickListener(this);
		mCamera.setOnClickListener(this);
		mSend.setOnClickListener(this);
		switch(type){
			case DBHelper.APP_TYPE_IMPORT_NOTICE:  //重要通知
				ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.send_type2, R.layout.simple_spinner_item);
		        adapter.setDropDownViewResource(R.layout.simple_spinner_dropdown_item);
		        mSendType.setAdapter(adapter);
//		        if(mLeader!=null && mLeader.equals(DBHelper.STATUS.LEADER_HIGHT)){
//		        	mSendType.setEnabled(false);
//		        	ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.send_type, R.layout.simple_spinner_item);
//			        adapter.setDropDownViewResource(R.layout.simple_spinner_dropdown_item);
//			        mSendType.setAdapter(adapter);
//		        }else if(mLeader!=null && mLeader.equals(DBHelper.STATUS.LEADER_MIDDLE)){
//		        	ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.send_type2, R.layout.simple_spinner_item);
//			        adapter.setDropDownViewResource(R.layout.simple_spinner_dropdown_item);
//			        mSendType.setAdapter(adapter);
//		        }else{
//		        	ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.send_type, R.layout.simple_spinner_item);
//			        adapter.setDropDownViewResource(R.layout.simple_spinner_dropdown_item);
//			        mSendType.setAdapter(adapter);
//		        }
				break;
			case DBHelper.APP_TYPE_ME_REPORT://我要报告
				mPerson.setVisibility(View.GONE);
				mAdd.setVisibility(View.GONE);
				mPersons = "0";
				mSendType.setVisibility(View.GONE);
				TextView tv = (TextView)findViewById(R.id.tv_hint);
				tv.setVisibility(View.GONE);
				break;
			
		}
	}
	
	public boolean sendCheck()
	{
		boolean isGood = true;
		mPerson = (EditText)findViewById(R.id.et_person);
		mContent = (EditText)findViewById(R.id.et_content);
			
		if (mPerson.getText().toString().length() == 0 && mContent.getText().toString().length() == 0)
		{
			mBuilder.setMessage(R.string.send_both_null_exception)
			.setNegativeButton(R.string.btn_back, null)
			.show();
			isGood = false;
		}else if ( mPerson.getText().toString().length() == 0 && mContent.getText().toString().length() != 0 )
		{
			mBuilder.setMessage(R.string.send_receiver_null_exception)
			.setNegativeButton(R.string.btn_back, null)
			.show();
			isGood = false;
		}else if ( mPerson.getText().toString().length() != 0 && mContent.getText().toString().length() == 0 )
		{
			mBuilder.setMessage(R.string.send_content_null_exception)
			.setNegativeButton(R.string.btn_back, null)
			.show();
			isGood = false;
		}
		else
			isGood = true;
		
		return isGood;
		
	}
	
	public boolean sendCheck2()
	{
		boolean isGood = true;
		
		mContent = (EditText)findViewById(R.id.et_content);
			
		if (mContent.getText().toString().length() == 0 )
		{
			mBuilder.setMessage(R.string.send_content_null_exception)
			.setNegativeButton(R.string.btn_back, null)
			.show();
			isGood = false;
		}
		
		return isGood;
		
	}
	
	@Override
	public void onClick(View v) {
		switch(v.getId()){
		case R.id.btn_add:
			mPerson.setText("");
			mPersons="";
			showDailog();
			break;
		case R.id.btn_camera:
//			Tools.takePicture(this, REUQEST_CODE_TAKE_PICTURE);
			Intent getImage = new Intent(Intent.ACTION_GET_CONTENT);
	        getImage.addCategory(Intent.CATEGORY_OPENABLE);
	        getImage.setType("image/*");
	        startActivityForResult(getImage, REUQEST_CODE_TAKE_PICTURE); 
			break;
		case R.id.btn_send:
			if(mPersons!=null){
				String type = "";  //我要报告没有发送类型
				boolean isCheck = true;
				if(this.type == DBHelper.APP_TYPE_IMPORT_NOTICE ){
					type = (String)mSendType.getSelectedItem();
					isCheck = sendCheck();
				}else{
					type = "其他";
					isCheck = sendCheck2();
				}						
				if(isCheck)
					new SendTask().execute(type);
			}
			break;
		}
	}
	
	private View createHeaderView(final ListView lv){
		final CheckedTextView view = (CheckedTextView)mInflater.inflate(R.layout.simple_list_item_multiple_choice, null);
		view.setText(R.string.select_all);
		view.setOnTouchListener(new View.OnTouchListener() {		
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if(event.getAction() == MotionEvent.ACTION_DOWN){
					if(!view.isChecked()){//全选
						for(int i=0;i<lv.getCount();i++){
							lv.setItemChecked(i, true);
						}
					}
					else{//取消全选
						for(int i=0;i<lv.getCount();i++){
							lv.setItemChecked(i, false);
						}
					}
					return true;
				}
				return false;
			}
		});
		return view;
	}
	
	
	// 选择框的三个TAB页
	@Override
	public View createTabContent(String tag) {
		if(tag.equals("person")){
			LinearLayout ll = (LinearLayout)mInflater.inflate(R.layout.person, null);
			final ListView lv = (ListView)ll.findViewById(R.id.list1);
			mCursor = mDB.queryAll(DBHelper.TB_PERSON);
//			if(type!=DBHelper.APP_TYPE_WORK_REPORT || !DBHelper.STATUS.LEADER_SMALL.equals(mLeader)){
//				if(mLeader!=null && mLeader.equals(DBHelper.STATUS.LEADER_HIGHT)){
//					mCursor = mDB.queryAll(DBHelper.TB_PERSON2);
//				}
//				else{
//					mCursor = mDB.queryAll(DBHelper.TB_PERSON);
//				}
//			}
//			else{
//				mCursor = mDB.queryNotAll(DBHelper.TB_PERSON,new String[]{DBHelper.FIELD_PERSON_IS_LEADER},new String[]{DBHelper.STATUS.LEADER_HIGHT});
//			}
			mAdapter = new SimpleCursorAdapter(this, R.layout.simple_list_item_multiple_choice, mCursor, new String[]{DBHelper.FIELD_PERSON_NAME}, new int[]{android.R.id.text1});
			lv.addHeaderView(createHeaderView(lv));
			lv.setAdapter(mAdapter);
			Button b = (Button)ll.findViewById(R.id.btn_sure);
			b.setOnClickListener(new OnClickListener() {	
				@Override
				public void onClick(View v) {
					boolean flag = false;
					String person = mPerson.getText().toString();
					for(int i=1;i<lv.getCount();i++){
						if(lv.isItemChecked(i)){
							flag = mCursor.moveToPosition(i-1);
							if(flag){
								if(!person.equals("")){
									person+=";";
									mPersons+=";";
								}
								person+=mCursor.getString(mCursor.getColumnIndexOrThrow(DBHelper.FIELD_PERSON_NAME));
								mPersons+=mCursor.getString(mCursor.getColumnIndexOrThrow(DBHelper.FIELD_PERSON_ID));
							}
						}
					}
					mPerson.setText(removeDuplicate(person));
					mPersons = removeDuplicate(mPersons);
					if(mDialog!=null) mDialog.dismiss();
				}
			});
			return ll;
		}
		else if(tag.equals("department")){
			LinearLayout ll = (LinearLayout)mInflater.inflate(R.layout.person, null);
			final ListView lv = (ListView)ll.findViewById(R.id.list1);
			mCursor = mDB.queryAll(DBHelper.TB_DEPARTMENT);
//			if(type!=DBHelper.APP_TYPE_WORK_REPORT || !DBHelper.STATUS.LEADER_SMALL.equals(mLeader)){
//				mCursor = mDB.queryAll(DBHelper.TB_DEPARTMENT);
//			}
//			else{
//				mCursor = mDB.queryNotAll(DBHelper.TB_DEPARTMENT,new String[]{DBHelper.FIELD_DEPARTMENT_NAME},new String[]{"总经理室"});
//			}
			mAdapter = new SimpleCursorAdapter(this, R.layout.simple_list_item_multiple_choice, mCursor, new String[]{DBHelper.FIELD_PERSON_NAME}, new int[]{android.R.id.text1});
			lv.addHeaderView(createHeaderView(lv));
			lv.setAdapter(mAdapter);
			Button b = (Button)ll.findViewById(R.id.btn_sure);
			b.setOnClickListener(new OnClickListener() {	
				@Override
				public void onClick(View v) {
					boolean flag = false;
					String person = mPerson.getText().toString();
					Cursor c = null;
					for(int i=1;i<lv.getCount();i++){
						if(lv.isItemChecked(i)){
						flag = mCursor.moveToPosition(i-1);
						if(flag){ 
							c = mDB.queryAll(DBHelper.TB_PERSON, new String[]{DBHelper.FIELD_PERSON_DEPARTMENT}, new String[]{mCursor.getString(mCursor.getColumnIndexOrThrow(DBHelper.FIELD_DEPARTMENT_ID))});
							if(c!=null && c.getCount()>0){
								c.moveToFirst();
								do{
									if(!mPersons.equals("")) {
										mPersons+=";";
									}
									mPersons+=c.getString(c.getColumnIndexOrThrow(DBHelper.FIELD_PERSON_ID));
								}
								while(c.moveToNext());
							}
							c = mDB.queryAll(DBHelper.TB_DEPARTMENT, new String[]{DBHelper.FIELD_ID}, new String[]{mCursor.getString(mCursor.getColumnIndexOrThrow(DBHelper.FIELD_ID))});
							if(c!=null && c.getCount()>0){
								c.moveToFirst();
								if(!person.equals("")) {
									person+=";";
								}
								person+=c.getString(c.getColumnIndexOrThrow(DBHelper.FIELD_DEPARTMENT_NAME));
							}
						  }
						}
					}
					mPerson.setText(removeDuplicate(person));
					mPersons = removeDuplicate(mPersons);
					if(mDialog!=null) mDialog.dismiss();
					if(c!=null) c.close();
				}
			});
			return ll;
		}
		else{
			LinearLayout ll = (LinearLayout)mInflater.inflate(R.layout.person, null);
			final ListView lv = (ListView)ll.findViewById(R.id.list1);
			mCursor = mDB.queryAll(DBHelper.TB_POSITION);
//			if(type!=DBHelper.APP_TYPE_WORK_REPORT || !DBHelper.STATUS.LEADER_SMALL.equals(mLeader)){
//				mCursor = mDB.queryAll(DBHelper.TB_POSITION);
//			}
//			else{
//				mCursor = mDB.queryNotAll(DBHelper.TB_POSITION,new String[]{DBHelper.FIELD_POSITION_NAME},new String[]{"指挥中心"});
//			}
			mAdapter = new SimpleCursorAdapter(this, R.layout.simple_list_item_multiple_choice, mCursor, new String[]{DBHelper.FIELD_PERSON_NAME}, new int[]{android.R.id.text1});
			lv.addHeaderView(createHeaderView(lv));
			lv.setAdapter(mAdapter);
			Button b = (Button)ll.findViewById(R.id.btn_sure);
			b.setOnClickListener(new OnClickListener() {	
				@Override
				public void onClick(View v) {
					boolean flag = false;
					String person = mPerson.getText().toString();
					Cursor c = null;
					for(int i=1;i<lv.getCount();i++){
						if(lv.isItemChecked(i)){
						flag = mCursor.moveToPosition(i-1);
						if(flag){
							String where = " "+DBHelper.FIELD_PERSON_POSITION+" like ? or "+DBHelper.FIELD_PERSON_POSITION+" like ? or "+DBHelper.FIELD_PERSON_POSITION+" like ? or "+DBHelper.FIELD_PERSON_POSITION+" = ? ";
							c = mDB.queryLikeAll(DBHelper.TB_PERSON,where, new String[]{"%,"+mCursor.getString(mCursor.getColumnIndexOrThrow(DBHelper.FIELD_POSITION_ID))+",%",mCursor.getString(mCursor.getColumnIndexOrThrow(DBHelper.FIELD_POSITION_ID))+",%","%,"+mCursor.getString(mCursor.getColumnIndexOrThrow(DBHelper.FIELD_POSITION_ID)),mCursor.getString(mCursor.getColumnIndexOrThrow(DBHelper.FIELD_POSITION_ID))},null);
							if(c!=null && c.getCount()>0){
								c.moveToFirst();
								do{
									if(!mPersons.equals("")) {
										mPersons+=";";
									}
									mPersons+=c.getString(c.getColumnIndexOrThrow(DBHelper.FIELD_PERSON_ID));
								}
								while(c.moveToNext());
							}
							c = mDB.queryAll(DBHelper.TB_POSITION, new String[]{DBHelper.FIELD_ID}, new String[]{mCursor.getString(mCursor.getColumnIndexOrThrow(DBHelper.FIELD_ID))});
							if(c!=null && c.getCount()>0){
								c.moveToFirst();
								if(!person.equals("")) {
									person+=";";
								}
								person+=c.getString(c.getColumnIndexOrThrow(DBHelper.FIELD_DEPARTMENT_NAME));
							}
						}
					  }
					}
					mPerson.setText(removeDuplicate(person));
					mPersons = removeDuplicate(mPersons);
					if(mDialog!=null) mDialog.dismiss();
					if(c!=null) c.close();
				}
			});
			return ll;
		}
	}
	
	/*
	 * 去掉重复
	 */
	public static String removeDuplicate(String str)   
	{   
		if(str!=null && !"".equals(str)){
			String[] values = str.split(";");
			ArrayList<String> list = new ArrayList<String>();
			int len = values.length;
			for(int i=0;i<len;i++){
				if(!list.contains(values[i])) list.add(values[i]);
			}
			return TextUtils.join(";", list);
		}
		return str;
	}  
	
	private View buildLabel(int label){
    	LayoutInflater inflater = getLayoutInflater();
    	Button btn = (Button)inflater.inflate(R.layout.label, null);
    	btn.setText(label);
    	return btn;
    }
	
	/*
	 * 创建对话框
	 * 
	 * @param info
	 */
	private void showDailog() {
		mDialog = new Dialog(this);
		mDialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
		mDialog.getWindow().setLayout(480, 650);
		View view = getLayoutInflater().inflate(
				R.layout.select_person_dialog, null);
		TabHost host = (TabHost)view.findViewById(android.R.id.tabhost);
		host.setup();
		if(mLeader!=null && mLeader.equals(DBHelper.STATUS.LEADER_HIGHT)){
			host.addTab(host.newTabSpec("person").setIndicator(buildLabel(R.string.person)).setContent(this));
		}else{
			host.addTab(host.newTabSpec("position")
						.setIndicator(buildLabel(R.string.position))
						.setContent(this));
			host.addTab(host.newTabSpec("person")
					.setIndicator(buildLabel(R.string.person))
					.setContent(this));
			host.addTab(host.newTabSpec("department")
					.setIndicator(buildLabel(R.string.department))
					.setContent(this));
		}
		mDialog.setContentView(view);
		mDialog.show();
	}
	
	class SendTask extends CommonTask<String>{
		private Response mResponse;
		private String mType;
		public SendTask(){
			super(SendActivity.this,getString(R.string.sending));
		}
		
		@Override
		protected Void doInBackground(String... params) {
			try {
				mType = params[0];
				String mResult = HttpManager.insertImportNotice(SendActivity.this,SendActivity.this.type,Tools.splitString(mPersons),mContent.getText().toString().trim(),mType,null,mPictrueStream);
				Log.e("---------send ImportNotice Result : ",mResult);
				mResponse = JsonParse.parseRespnse(mResult);
				
			} catch (Exception e) {
				mResponse = null;
			}
			return null;
		}
		
		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			if(mResponse!=null&&mResponse.success){
				mBuilder.setMessage(R.string.import_notice_send_success).setNegativeButton(R.string.btn_back,null).show();
				mDB.insertImportNoticeSent(SendActivity.this.type,Tools.splitString(mPersons),mContent.getText().toString().trim(),mType,"",mResponse.id);
				Intent i;
				switch(type){
					case 1: i = new Intent(SendActivity.this,ImportNoticeActivity.class);
						   i.putExtra("type",2); 
						   break;
					case 2:i = new Intent(SendActivity.this,MeReportActivity.class);
					       i.putExtra("type",1); 
						   break;
					default:i = new Intent(SendActivity.this,ImportNoticeActivity.class);
					       i.putExtra("type",2); 
						   break;
				}
				 
				startActivity(i);
				finish();
			}else{
				mBuilder.setMessage(R.string.import_notice_send_fail).setNegativeButton(R.string.btn_back,null).show();
				Log.e(this.getClass().getName()+"---------send ImportNotice error : ",String.valueOf(mResponse));
			}
		}
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		CommonActivity.isSend = false;
	}
}
